﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Common.Library.Db
{
    /// <summary>
    /// SQL语句生成器
    /// </summary>
    public class SqlBuilder
    {

        /// <summary>
        /// Insert语句生成器
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="entity">数据实体</param>
        /// <param name="tableName">表名，如果为空默认取类型上面的特性，如果特性不存在，取类型的名字</param>
        /// <returns></returns>
        public static string InsertBuilder<T>(T entity, string tableName = "")
        {
            Type t = typeof(T);
            //PropertyInfo[] PropertyList = t.GetProperties();

            //if (string.IsNullOrEmpty(tableName))
            //{
            //    object[] objs = t.GetCustomAttributes(typeof(EntityTableName), true);
            //    foreach (var item in objs)
            //    {
            //        EntityTableName attr = item as EntityTableName;
            //        if (attr != null)
            //        {

            //            tableName = attr.TableName;//表名只有获取一次
            //            break;
            //        }
            //    }
            //}

            string columns = GetColmons(t);
            if (string.IsNullOrEmpty(columns))
            {
                return string.Empty;
            }
            string values = GetValues(t);
            if (string.IsNullOrEmpty(values))
            {
                return string.Empty;
            }
            StringBuilder sql = new StringBuilder();
            sql.Append("Insert into " + tableName);
            sql.Append("(" + columns + ")");
            sql.Append(" values(" + values + ")");
            return sql.ToString();
        }

        /// <summary>
        /// 获得类型的列名
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static string GetColmons<T>(T obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            return string.Join(",", obj.GetType().GetProperties().Select(p => p.Name).ToList());
        }
        /// <summary>
        /// 获得值
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static string GetValues<T>(T obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            return string.Join(",", obj.GetType().GetProperties().Select(p => string.Format("'{0}'", p.GetValue(obj))).ToArray());
        }

    }



    /// <summary>
    /// 数据库中的表名字
    /// </summary>
    public class EntityTableName : Attribute
    {
        public string TableName { get; set; }
        public EntityTableName(string tableName)
        {
            TableName = tableName;
        }
    }


}
